package com.sn.shop.exception;

import com.sn.shop.enums.ResultStatus;
import com.sn.shop.utils.ReturnResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther sn
 * @date 2018/2/9
 * @description 全局异常捕获器
 */

@RestController
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ReturnResult baseErrorHandler(Exception ex) throws Exception {
        ex.printStackTrace();
        ReturnResult rst;
        if (ex instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException pe = (MissingServletRequestParameterException) ex;
            rst = ReturnResult.error(ResultStatus.PARAMETER_REQUIRED, "关键参数【" + pe.getParameterName() + ":" + pe.getParameterType() + "】不能缺失！");
            // return new ResponseEntity(HttpStatus.MOVED_PERMANENTLY);
        } else if(ex instanceof UsernameNotFoundException) {
            rst = ReturnResult.error(ResultStatus.USERNAME_NOT_FOUND, ResultStatus.USERNAME_NOT_FOUND.getDesc());
        } else if(ex instanceof BadCredentialsException){
            rst = ReturnResult.error(ResultStatus.BAD_CREDENTIALS, ResultStatus.BAD_CREDENTIALS.getDesc());
        } else {
            rst = ReturnResult.error(ResultStatus.OTHER_ERROR, ResultStatus.OTHER_ERROR.getDesc());
            //  return new ResponseEntity(HttpStatus.MOVED_PERMANENTLY);
        }
        return rst;
    }
}
